package com.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.common.api.ApprovalApi;
import com.common.core.domain.AjaxResult;
import com.common.core.domain.entity.SysUser;
import com.common.utils.CurrentRoleUtils;
import com.common.utils.QueryWrapperUtils;
import com.common.utils.SecurityUtils;
import com.common.utils.StringUtils;
import com.common.utils.bean.BizProcessMessages;
import com.common.utils.bean.ReflectionUtils;
import com.common.utils.uuid.IdUtils;
import com.domain.bo.ResearchServiceBo;
import com.domain.entity.EthicalReview;
import com.domain.entity.ResearchService;
import com.domain.vo.FileInfos;
import com.domain.vo.NavigationVo;
import com.domain.vo.ResServListVo;
import com.flowable.domain.vo.task.BpmTaskApproveReqVO;
import com.flowable.service.IFlowTaskService;
import com.mapper.ResearchServMapper;
import com.service.IResearchServService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ResearchServImpl implements IResearchServService {

    @Autowired
    private ResearchServMapper researchServMapper;

    @Autowired
    private ApprovalApi approvalApi;

    @Autowired
    private IFlowTaskService flowTaskService;

    @Autowired
    private EthicalReviewImpl ethicalReviewService;

    /**
     * 左上角根据状态的数量统计
     * @param researchServiceBo
     * @return
     */
    public List<NavigationVo.NameAndCount> selectGroups(ResearchServiceBo researchServiceBo){
        List<NavigationVo.NameAndCount> res = new ArrayList<>();
        try{
            QueryWrapper<NavigationVo.NameAndCount> queryWrapper = new QueryWrapper<>();
            queryWrapper = this.getCondition(queryWrapper,researchServiceBo,"group");//拼条件
            QueryWrapperUtils.getParamsEthicalBusiness(queryWrapper,SecurityUtils.getLoginUser().getUser(),"resServ");//用户权限

            res = researchServMapper.selectGroups(queryWrapper,researchServiceBo);
        }catch (Exception exception){
            String ex = exception.getMessage();
            res = null;
        }
        return res;
    }

    @Override
    public IPage<ResServListVo> selectList(ResearchServiceBo researchServiceBo,String operateType) {
        IPage<ResServListVo> res = new Page<>();
        try {
            QueryWrapper<ResServListVo> queryWrapper = new QueryWrapper<>();
            queryWrapper = this.getCondition(queryWrapper,researchServiceBo,"list");//拼条件
            QueryWrapperUtils.getParamsEthicalBusiness(queryWrapper,SecurityUtils.getLoginUser().getUser(),"resServ");//用户权限

            if(operateType.equals("list")){
                IPage<ResServListVo> myPage = new Page<>(researchServiceBo.getPageNo(), researchServiceBo.getPageSize());
                res = researchServMapper.selectListInfos(myPage,queryWrapper,researchServiceBo);
                res = ethicalReviewService.getCheckInfosForList(res,"科研服务",ResServListVo::setTaskId,ResServListVo::setIsAuditor,ResServListVo::getProcessInstanceId);
            }else{
                IPage<ResServListVo> myPage = new Page<>(1, 1000);
                res = researchServMapper.selectListInfos(myPage,queryWrapper,researchServiceBo);
            }
        }catch(Exception exception){
            String ex = exception.getMessage();
        }
        return res;
    }

    /**
     * 拼条件
     * @param queryWrapper
     * @param researchServiceBo
     * @return
     */
    private QueryWrapper getCondition(QueryWrapper queryWrapper,ResearchServiceBo researchServiceBo,String funcType){
        try{
            //处理服务类型id
            researchServiceBo.setServiceType(addQuotationToStr(researchServiceBo.getServiceType()));

            //处理结项日期字段（年份4、年月7、年月日）
            String startAcceptTime = ethicalReviewService.changeDateString(researchServiceBo.getStartTime(),"start");
            String endAcceptTime = ethicalReviewService.changeDateString(researchServiceBo.getEndTime(),"end");

            queryWrapper.like(StringUtils.isNotBlank(researchServiceBo.getApplyer()),"APPLYER",researchServiceBo.getApplyer())
                    .ge(StringUtils.isNotBlank(startAcceptTime), "APPLY_TIME", startAcceptTime)
                    .le(StringUtils.isNotBlank(endAcceptTime), "APPLY_TIME", endAcceptTime);
            if(funcType.equals("list")){
                queryWrapper.eq(StringUtils.isNotBlank(researchServiceBo.getCheckstatusByGroup()), "CHECKSTATUS", researchServiceBo.getCheckstatusByGroup());
            }

            return queryWrapper;
        }catch (Exception exception){
            return queryWrapper;
        }
    }

    public ResearchService selectResearchServiceByID(String id) {
        try {
            ResearchService res = researchServMapper.selectResearchServiceByID(id);
            if(res != null){
                res.setFileInfoList(getFileInfos(res.getFileId()));
            }
            return res;
        } catch (Exception exception) {
            return new ResearchService();
        }
    }

    public AjaxResult saveResServ(ResearchService researchServ) {
        String researchServId = "";
        String processInstanceId = "";
        String currentRoleKey = CurrentRoleUtils.getCurrentRoleKey();

        if (researchServ != null) {
            Integer submitType = researchServ.getSubmitType();
            String checkStatus = researchServ.getCheckstatus();
            String operateType = StringUtils.isNotBlank(researchServ.getID()) ? "edit" : "add";

            if (submitType != null) {
                switch (submitType) {
                    case -1:
                        //暂存：新建编辑都只保存信息，不做任何其他操作
                        if(!currentRoleKey.equals("biz_kycgly") || !StringUtils.isNotBlank(checkStatus)){
                            researchServ.setCheckstatus("-1");//科研管理员、秘书的暂存都不改状态
                        }
                        researchServId = this.saveInfos(researchServ, operateType);
                        return StringUtils.isNotBlank(researchServId) ?
                            researchServId.contains("失败") ? AjaxResult.error(researchServId) :
                            AjaxResult.success(BizProcessMessages.SAVE_SUCCESS) :
                            AjaxResult.error(BizProcessMessages.SAVE_FAIL);
                    case 1:
                        researchServ.setCheckstatus("1");
                        researchServ = ReflectionUtils.updateFields(researchServ, ResearchService.class);
                        researchServId = this.saveInfos(researchServ, operateType);
                        if (StringUtils.isNotBlank(researchServId)) {
                            if (researchServId.contains("失败")) {
                                return AjaxResult.error(researchServId);
                            } else {
                                processInstanceId = approvalApi.businessEntryApproval(researchServId, "科研服务");
                                if (!StringUtils.isNotBlank(processInstanceId)) {
                                    researchServ.setCheckstatus("-1");
                                    this.saveInfos(researchServ, operateType);
                                    return AjaxResult.warn(BizProcessMessages.SAVE_PARTIAL_SUCCESS);
                                } else {
                                    return AjaxResult.success(BizProcessMessages.SAVE_SUCCESS);
                                }
                            }
                        } else {
                            return AjaxResult.error(BizProcessMessages.SAVE_FAIL);
                        }
                    case 2:
                        if (operateType.equals("add") || (operateType.equals("edit") &&
                            (!StringUtils.isNotBlank(checkStatus) || !checkStatus.equals("1")))) {
                            researchServ = ReflectionUtils.updateFields(researchServ, ResearchService.class);
                            researchServ.setProcessInstanceId("0");
                            researchServ.setCheckstatus("2");
                            researchServId = this.saveInfos(researchServ, operateType);
                            return StringUtils.isNotBlank(researchServId) ?
                                researchServId.contains("失败") ? AjaxResult.error(researchServId) :
                                AjaxResult.success(BizProcessMessages.SAVE_SUCCESS) :
                                AjaxResult.error(BizProcessMessages.SAVE_FAIL);
                        } else {
                            try {
                                researchServId = this.saveInfos(researchServ, operateType);
                                if (StringUtils.isNotBlank(researchServId)) {
                                    BpmTaskApproveReqVO bta = new BpmTaskApproveReqVO();
                                    bta.setId(researchServ.getTaskId());
                                    bta.setReason(SecurityUtils.getNickName() + "保存并通过");
                                    flowTaskService.approveTask(SecurityUtils.getUserId(), bta);
                                    return AjaxResult.success(BizProcessMessages.SAVE_SUCCESS);
                                } else {
                                    return AjaxResult.error(BizProcessMessages.SAVE_FAIL);
                                }
                            } catch (Exception exception) {
                                return AjaxResult.warn(BizProcessMessages.SAVE_SUCCESS_APPROVE_FAIL);
                            }
                        }
                    default:
                        return AjaxResult.error(BizProcessMessages.SAVE_FAIL);
                }
            } else {
                researchServ.setCheckstatus("-1");
                researchServId = this.saveInfos(researchServ, operateType);
                return StringUtils.isNotBlank(researchServId) ?
                    AjaxResult.success(BizProcessMessages.SAVE_SUCCESS) :
                    AjaxResult.error(BizProcessMessages.SAVE_FAIL);
            }
        } else {
            return AjaxResult.warn("未获取到科研服务信息！");
        }
    }

    public String saveInfos(ResearchService researchServ, String operateType) {
        String res = "";

        SysUser loginUser = SecurityUtils.getLoginUser().getUser();
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String researchServId = researchServ.getID();

        try {
            int saveRes = 0;
            researchServ.setLasteditdate(dateFormat.parse(dateFormat.format(date)));
            researchServ.setLasteditusername(loginUser.getNickName());
            researchServ.setLastedituserid(loginUser.getUserRealId());

            if (operateType.equals("add")) {
                researchServ.setCreatedate(dateFormat.parse(dateFormat.format(date)));
                researchServ.setCreateuserid(loginUser.getUserRealId());
                researchServ.setCreateusername(loginUser.getNickName());

                researchServId = IdUtils.simpleUUID();
                researchServ.setID(researchServId);
                saveRes = researchServMapper.insert(researchServ);
            } else {
                saveRes = researchServMapper.updateById(researchServ);
            }

            if (saveRes > 0) {
                res = researchServId;
            }
        } catch (Exception exception) {
            String ex = exception.getMessage();
        }

        return res;
    }

    public String deleteResServByIDs(String[] ids) {
        String res = "操作成功！";
        try {
            List<String> idList = Arrays.stream(ids).collect(Collectors.toList());
            idList.forEach(id -> {
                researchServMapper.deleteById(id);
            });
        } catch (Exception exception) {
            res = "操作失败！" + exception.getMessage();
        }
        return res;
    }

    public List<FileInfos> getFileInfos(String fileIds){
        try{
            return researchServMapper.getFileInfos(addQuotationToStr(fileIds));
        }catch (Exception exception){
            String ex = exception.getMessage();
            return null;
        }
    }

    /**
     * 给字符串加引号
     * @param oldStr
     * @return
     */
    public String addQuotationToStr(String oldStr){
        if(StringUtils.isNotBlank(oldStr)){
            String newStr = oldStr.replace(",","','");
            return newStr ;
        }else{
            return oldStr;
        }
    }
}
